/**
 * 基础菜单 商品管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <!-- <el-form-item label="搜索：">
        <el-input size="small" v-model="title" placeholder="输入商品名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item> -->

      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
      style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>

      <el-table-column prop="addTime" label="商品图片" width="100">
        <template slot-scope="scope">
          <el-image style="width: 80px; height: 80px;border-radius: 10px;" :src="scope.row.main_image"></el-image>
        </template>
      </el-table-column>
      <el-table-column sortable prop="title" label="商品标题" width="150">
      </el-table-column>
      <el-table-column sortable prop="status" label="状态" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-if="scope.row.status == 2">已下架</div>
          <div v-if="scope.row.status == 1">出售中</div>
        </template>

      </el-table-column>
      <el-table-column sortable prop="sales_volume" label="销量" width="120">
      </el-table-column>
      <el-table-column sortable prop="stock" label="库存" width="120">
      </el-table-column>

      <el-table-column sortable prop="integral" label="兑换所需积分" width="120">
      </el-table-column>



      <!-- <el-table-column sortable prop="editTime" label="创建时间" width="150">
        <template slot-scope="scope">
          <div>{{transformDate(scope.row.created_time)}}</div>
        </template>
      </el-table-column> -->



      <el-table-column align="center" label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" @click="belowCommodity(scope.$index, scope.row)" v-if="scope.row.status == 1">下架</el-button>
          <el-button size="mini" @click="upCommodity(scope.$index, scope.row)" v-if="scope.row.status == 2">上架</el-button>
          <el-button size="mini" type="danger" @click="deleteCommodity(scope.row.id)">删除</el-button>

        </template>
      </el-table-column>
    </el-table>




    <el-dialog :title="title" :visible.sync="editFormVisible" width="80%" @click="closeDialog">



      <el-form label-width="120px" ref="editForm">


        <el-form-item label="商品标题" prop="commodity_title">
          <el-input size="small" v-model="commodity_title" auto-complete="off" placeholder="商品标题"></el-input>
        </el-form-item>

        <el-form-item label="主图" style="">

          <div class="upload-demo">
            <el-upload action="" :http-request="mainImgUpload" :show-file-list="false" list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>



          </div>

          <div v-for="imageItem in commodity_imgs">
            <img class="avatar" style="width: 90px; height: 90px;" :src="imageItem">

          </div>

        </el-form-item>



        <el-form-item label="商品分类">


          <el-select v-model="category_id" placeholder="请选择">


            <el-option v-for="category in categoryList" :label="category.name" :value="category.id"></el-option>

          </el-select>


        </el-form-item>




        <el-form-item label="兑换所需积分" prop="commodity_title">
          <el-input size="small" v-model="integral" auto-complete="off" placeholder="兑换所需积分"></el-input>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input size="small" v-model="stock" auto-complete="off" placeholder="商品库存"></el-input>
        </el-form-item>

        <el-form-item label="商品描述" prop="deptName">

          <quill-editor v-model="detail" :options="editorOption" style="height: 200px;" ref="QuillEditor">
          </quill-editor>

        </el-form-item>

        <el-form-item label="" prop="commodity_title"></el-form-item>
        <el-form-item label="" prop="commodity_title"></el-form-item>

        <el-form-item label="" prop="commodity_title"></el-form-item>
        <el-form-item label="" prop="commodity_title"></el-form-item>

        <el-form-item label="" prop="commodity_title"></el-form-item>
        <el-form-item label="" prop="commodity_title"></el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer" style="z-index: 100000;">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="addCommodity()"
          v-if="title == '添加'">添加</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="updateCommodity()"
          v-if="title == '修改'">修改</el-button>
      </div>

    </el-dialog>




    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

  </div>
</template>

<script>
import { upCommodity,belowCommodity,updateCommodity, getCommodityStatus, addCommodity, getCategoryList, deleteCommodity } from '../../api/userMG'
import Pagination from '../../components/Pagination'
import client from "@/utils/ossClient.js";
import VueQuillEditor from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";

// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction

  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image", "video"], // 对于图片上传这是重点
  ["clean"], // remove formatting button
];
export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: "添加",


      id: 0,
      commodity_title: "",//商品标题
      subtitle: "",//小标题
      commodity_imgs: [],//商品图片
      order_quantity: 0,//限制用户订单数，0不限制
      category_id: "",//类型id
      category_name: "",//分类名字
      stock: "",//商品库存
      price: 0,//商品价格，默认商品规格第一个
      integral: 0,
      attribute_list: [{ "id": 31, "product_id": 33, "product_specs": { "斤": "1斤" }, "product_stock": 0, "product_price": 1800, "cost_price": "18" }],//商品规格
      detail: "",//商品描述
      main_image: "",//主图像




      cursorIndex: 0,
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: (value) => {
                if (value) {
                  // 在这里编写图片按钮点击操作
                  this.uploadVisible = true;
                  this.cursorIndex =
                    this.$refs.QuillEditor.quill.getSelection().index;
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      uploadVisible: false,




      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 20,
        total: 20
      },
      categoryList: []//商品分类
    }
  },
  // 注册组件
  components: {
    Pagination,
    VueQuillEditor
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getCommodityStatus(1)

    this.getCategoryList()
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {



    // 获取数据方法
    getCategoryList() {
      this.loading = true;

      getCategoryList().then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.categoryList = res.data.list;
          return;
        }
        this.$message({
          type: "info",
          message: res.msg,
        });
      });
    },
    //自定义上传方法..
    mainImgUpload(file) {

      //判断扩展名
      const tmpcnt = file.file.name.lastIndexOf(".");
      const exname = file.file.name.substring(tmpcnt + 1);
      const names = ["jpg", "jpeg", "webp", "png", "bmp"];
      if (names.indexOf(exname) < 0) {
        this.$message.error("不支持的格式!");
        return;
      }
      const fileName = file.file.uid + "." + exname;
      client
        .put(fileName, file.file)
        .then((res) => {
          if (res.url) {


            this.commodity_imgs.push(res.url)

          } else {
            this.$message.error("文件上传失败");
          }
        })
        .catch((err) => { });
    },



    // 
    deleteCommodity(id) {


      var formData = {

        id: id,//


      };




      deleteCommodity(formData).then(res => {
        this.$message({
          type: 'info',
          message: res.msg
        })
        var self = this;
        setTimeout(() => {
          self.getCommodityStatus(1)
        }, 1000);
      })
        .catch(err => {
          this.loading = false
        })

    },
    // 
    addCommodity() {


      var formData = {

        title: this.commodity_title,//商品标题
        subtitle: this.subtitle,//小标题
        main_image: this.commodity_imgs[0],//主图
        sub_images: JSON.stringify(this.commodity_imgs),//轮播图
        attribute_list: JSON.stringify(this.attribute_list),//规格
        detail: this.detail,//描述
        category_id: this.category_id,//分类id、
        order_quantity: this.order_quantity,//是否限制订单数量
        isUpSpecification: 0,//是否修改规格，0不修改，1修改
        line_price: 0,
        integral: this.integral,//积分
        stock: this.stock//库存
        

      };




      addCommodity(formData).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'info',
            message: res.msg
          })
          this.editFormVisible = false
          this.getCommodityStatus(1)
        } else {
          this.$message({
            type: 'info',
            message: res.msg
          })
        }
      })
        .catch(err => {
          this.loading = false
        })

    },
    getMainImg(goodsData) {
      console.log(goodsData)
      return JSON.parse(goodsData.carousel)[0]

    },
    // 获取商品列表
    getCommodityStatus(page) {
      this.loading = true;
      var parameter = {
        key: "",
        page: (page - 1) * 20,
      };
      getCommodityStatus(parameter).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.listData = res.data.data;
          this.pageparm.currentPage = page;
          this.pageparm.total = res.data.count;
          return;
        }
        this.$message({
          type: "info",
          message: res.msg,
        });
      });
    },
    // 分页插件事件
    callFather(parm) {
      console.log(parm)
      this.pageparm.currentPage = parm.currentPage;
      this.getCommodityStatus(parm.currentPage)
    },
    // 搜索事件
    search() {
      this.getGoodsList(1)
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改'

        console.log(row)
        this.id = row.id;
        this.commodity_title = row.title;
        this.subtitle = row.subtitle;
        this.commodity_imgs = JSON.parse(row.sub_images);
        this.detail = row.detail;
        this.category_id = row.category_id;
        this.order_quantity = row.order_quantity;
        this.isUpSpecification = 0;
        this.line_price = 0;
        this.integral = row.integral;

        this.stock = row.stock;






      } else {
        this.title = '添加'
        this.id = 0;
        this.commodity_title = "";
        this.subtitle = "";
        this.commodity_imgs = [];
        this.detail = "";
        this.category_id = "";
        this.order_quantity = 0;
        this.isUpSpecification = 0;
        this.line_price = 0;
        this.integral = 0;
        this.stock = 0;


      }
    },
    // 
    updateCommodity(index, row) {


      var formData = {
        id: this.id,//商品标题
        title: this.commodity_title,//商品标题
        subtitle: this.subtitle,//小标题
        main_image: this.commodity_imgs[0],//主图
        sub_images: JSON.stringify(this.commodity_imgs),//轮播图
        attribute_list: JSON.stringify(this.attribute_list),//规格
        detail: this.detail,//描述
        category_id: this.category_id,//分类id、
        order_quantity: this.order_quantity,//是否限制订单数量
        isUpSpecification: 0,//是否修改规格，0不修改，1修改
        line_price: 0,
        integral: this.integral,//积分
        stock: this.stock//库存

      };

      console.log(formData)

      updateCommodity(formData).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'info',
            message: res.msg
          })
          this.editFormVisible = false
          this.getCommodityStatus(1)
        } else {
          this.$message({
            type: 'info',
            message: res.msg
          })
        }
      })
        .catch(err => {
          this.loading = false
        })
    },
    // 
    belowCommodity(index, row) {
      this.$confirm('确定要下架商品吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          belowCommodity({ id: row.id })
            .then(res => {
              if (res.code == 200) {

                this.getCommodityStatus(1)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
            })
        })
        .catch(() => {

        })
    },
    upCommodity(index, row) {
      this.$confirm('确定要上架商品吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          upCommodity({ id: row.id })
            .then(res => {
              if (res.code == 200) {

                this.getCommodityStatus(1)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
            })
        })
        .catch(() => {

        })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.userRole {
  width: 100%;
}
</style>

 
 